package com.easyoffer.nacos;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.client.config.NacosConfigService;
import com.easyoffer.common.util.BlackIpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.Executor;

@Component
@Data
@Slf4j
public class NacosListener implements InitializingBean {
    @Value("${nacos.black-list.data-id}")
    private String dataId;

    @Value("${nacos.black-list.group}")
    private String group;

    @Resource
    ConfigService configService ;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("nacos 监听器启动");
        String config = configService.getConfigAndSignListener(dataId, group, 3000L, new Listener() {
            // 通过线程池异步处理黑名单变化的逻辑,这里我们不需要，因为更新黑名单的逻辑是并不频繁
            @Override
            public Executor getExecutor() {
                return null;
            }

            // 监听后续黑名单变化
            @Override
            public void receiveConfigInfo(String configInfo) {
                log.info("监听到配置信息变化：{}", configInfo);
                BlackIpUtil.rebuildBlackIp(configInfo);
            }
        });
        // 初始化黑名单
        BlackIpUtil.rebuildBlackIp(config);
    }
}
